<?php
declare(strict_types=1);

namespace app\admin\service;

use app\admin\model\Order as OrderModel;

class OrderService
{
    /**
     * 过去指定时间内订单（折线图）
     * @param $where
     * @return mixed
     */
    public static function getOrderPriceLine($where)
    {
        $startEndTime = getStartEndTime(6);
        $orderPrice = OrderModel::getOrderPriceLine($where, $startEndTime['startTime'], $startEndTime['endTime']);
        return inArr($orderPrice, $startEndTime['dateArr']);
    }

    /**
     * 订单总金额
     * @param array $where
     * @return float
     */
    public static function orderTotalPayPrice($where = [])
    {
        return OrderModel::orderTotalPayPrice($where);
    }

    /**
     * 订单总金额（折线图）
     * @return mixed
     */
    public static function orderTotalPayPriceLine()
    {
        $startEndTime = getStartEndTime();

        $data = OrderModel::orderTotalPayPriceLine($startEndTime['startTime'], $startEndTime['endTime']);

        return inArr($data, $startEndTime['dateArr']);
    }

    /**
     * 总退款
     * @param array $where
     * @return float
     */
    public static function orderTotalRefundPrice($where = [])
    {
        return OrderModel::orderTotalRefundPrice($where);
    }

    /**
     * 总退款（折线图）
     * @return mixed
     */
    public static function orderTotalRefundPriceLine()
    {
        $startEndTime = getStartEndTime();

        $data = OrderModel::orderTotalRefundPriceLine($startEndTime['startTime'], $startEndTime['endTime']);

        return inArr($data, $startEndTime['dateArr']);
    }

    /**
     * 当日支付金额
     * @param array $where
     * @return float
     */
    public static function orderTodayPayPrice($where = [])
    {
        return OrderModel::orderTodayPayPrice($where);
    }

    /**
     * 订单数据
     * @return array
     */
    public static function getOrderData()
    {
        // 订单总金额
        $totalPayPrice = sprintf("%.2f", self::orderTotalPayPrice());
        // 当日订单金额
        $todayPayPrice = sprintf("%.2f", self::orderTodayPayPrice());
        // 总退款
        $totalRefundPrice = sprintf("%.2f", self::orderTotalRefundPrice());
        // 当天退款
        $todayRefundPrice = sprintf("%.2f", OrderModel::orderTodayRefundPrice());

        // 108年会员
        $orderYearPrice = self::getOrderYearPrice();
        // 108年会员 - 总金额
        $memberYearPrice = $orderYearPrice['memberYearPrice'];
        // 108年会员 - 当日金额
        $memberYearTodayPrice = $orderYearPrice['memberYearTodayPrice'];

        // 8.8月会员
        $orderMonthPrice = self::getOrderMonthPrice();
        // 8.8月会员 - 总金额
        $memberMonthPrice = $orderMonthPrice['memberMonthPrice'];
        // 8.8月会员 - 当日金额
        $memberMonthTodayPrice = $orderMonthPrice['memberMonthTodayPrice'];

        // 社群礼包
        $orderResourcePrice = self::getOrderResourcePrice();
        // 总金额
        $resourceTotalPrice = $orderResourcePrice['resourceTotalPrice'];
        // 当日金额
        $resourceTodayPrice = $orderResourcePrice['resourceTodayPrice'];

        // 订阅需求
        $orderDemandPrice = self::getOrderDemandPrice();
        // 总金额
        $demandTotalPrice = $orderDemandPrice['demandTotalPrice'];
        // 当日金额
        $demandTodayPrice = $orderDemandPrice['demandTodayPrice'];
        // 当日退款
        $demandRefundPrice = $orderDemandPrice['demandRefundPrice'];

        $totalPayPriceArr = explode('.', $totalPayPrice);
        $todayPayPriceArr = explode('.', $todayPayPrice);
        $totalRefundPriceArr = explode('.', $totalRefundPrice);
        $todayRefundPriceArr = explode('.', $todayRefundPrice);

        return [
            'totalPayPrice' => [
                'integer' => $totalPayPriceArr[0],
                'decimal' => $totalPayPriceArr[1],
            ],
            'todayPayPrice' => [
                'integer' => $todayPayPriceArr[0],
                'decimal' => $todayPayPriceArr[1],
            ],
            'totalRefundPrice' => [
                'integer' => $totalRefundPriceArr[0],
                'decimal' => $totalRefundPriceArr[1],
            ],
            'todayRefundPrice' => [
                'integer' => $todayRefundPriceArr[0],
                'decimal' => $todayRefundPriceArr[1],
            ],
            'memberYearPrice' => $memberYearPrice,
            'memberYearTodayPrice' => $memberYearTodayPrice,
            'memberMonthPrice' => $memberMonthPrice,
            'memberMonthTodayPrice' => $memberMonthTodayPrice,
            'resourceTotalPrice' => $resourceTotalPrice,
            'resourceTodayPrice' => $resourceTodayPrice,
            'demandTotalPrice' => $demandTotalPrice,
            'demandTodayPrice' => $demandTodayPrice,
            'demandRefundPrice' => $demandRefundPrice,
        ];
    }

    /**
     * 108年会员
     * @return array
     */
    public static function getOrderYearPrice()
    {
        $yearWhere = ['mid' => 1, 'type_id' => 1];
        // 108年会员 - 总金额
        $memberYearPrice = sprintf("%.2f", self::orderTotalPayPrice($yearWhere));
        // 108年会员 - 当日金额
        $memberYearTodayPrice = sprintf("%.2f", self::orderTodayPayPrice($yearWhere));
        // 订单总数
        $memberYearOrderTotal = OrderModel::orderTotalNums($yearWhere);
        // 当天订单总数
        $memberYearOrderTodayTotal = OrderModel::orderTodayTotalNums($yearWhere);

        return [
            'memberYearPrice' => $memberYearPrice,
            'memberYearTodayPrice' => $memberYearTodayPrice,
            'memberYearOrderTotal' => $memberYearOrderTotal,
            'memberYearOrderTodayTotal' => $memberYearOrderTodayTotal,
            'memberYearOrderLastTotal' => $memberYearOrderTotal - $memberYearOrderTodayTotal
        ];
    }

    /**
     * 8.8月会员
     * @return array
     */
    public static function getOrderMonthPrice()
    {
        $monthWhere = ['mid' => 3, 'type_id' => 1];
        // 8.8月会员 - 总金额
        $memberMonthPrice = sprintf("%.2f", self::orderTotalPayPrice($monthWhere));
        // 8.8月会员 - 当日金额
        $memberMonthTodayPrice = sprintf("%.2f", self::orderTodayPayPrice($monthWhere));
        // 订单总数
        $memberMonthOrderTotal = OrderModel::orderTotalNums($monthWhere);
        // 当天订单总数
        $memberMonthOrderTodayTotal = OrderModel::orderTodayTotalNums($monthWhere);

        return [
            'memberMonthPrice' => $memberMonthPrice,
            'memberMonthTodayPrice' => $memberMonthTodayPrice,
            'memberMonthOrderTotal' => $memberMonthOrderTotal,
            'memberMonthOrderTodayTotal' => $memberMonthOrderTodayTotal,
            'memberMonthOrderLastTotal' => $memberMonthOrderTotal - $memberMonthOrderTodayTotal,
        ];
    }

    /**
     * 社群礼包
     * @return array
     */
    public static function getOrderResourcePrice()
    {
        $resourceWhere = ['mid' => 7, 'type_id' => 15];
        // 总金额
        $resourceTotalPrice = sprintf("%.2f", self::orderTotalPayPrice($resourceWhere));
        // 当日金额
        $resourceTodayPrice = sprintf("%.2f", self::orderTodayPayPrice($resourceWhere));
        // 订单总数
        $resourceOrderTotal = OrderModel::orderTotalNums($resourceWhere);
        // 当天订单总数
        $resourceOrderTodayTotal = OrderModel::orderTodayTotalNums($resourceWhere);

        return [
            'resourceTotalPrice' => $resourceTotalPrice,
            'resourceTodayPrice' => $resourceTodayPrice,
            'resourceOrderTotal' => $resourceOrderTotal,
            'resourceOrderTodayTotal' => $resourceOrderTodayTotal,
            'resourceOrderLastTotal' => $resourceOrderTotal - $resourceOrderTodayTotal,
        ];
    }

    /**
     * 订阅需求
     * @return array
     */
    public static function getOrderDemandPrice()
    {
        $demandWhere = ['type_id' => 14];
        // 总金额
        $demandTotalPrice = sprintf("%.2f", self::orderTotalPayPrice($demandWhere));
        // 当日金额
        $demandTodayPrice = sprintf("%.2f", self::orderTodayPayPrice($demandWhere));
        // 当日退款
        $demandRefundPrice = sprintf("%.2f", self::orderTodayPayPrice($demandWhere));
        // 订单总数
        $demandOrderTotal = OrderModel::orderTotalNums($demandWhere);
        // 当天订单总数
        $demandOrderTodayTotal = OrderModel::orderTodayTotalNums($demandWhere);

        return [
            'demandTotalPrice' => $demandTotalPrice,
            'demandTodayPrice' => $demandTodayPrice,
            'demandRefundPrice' => $demandRefundPrice,
            'demandOrderTotal' => $demandOrderTotal,
            'demandOrderTodayTotal' => $demandOrderTodayTotal,
            'demandOrderLastTotal' => $demandOrderTotal - $demandOrderTodayTotal,
        ];
    }

    /**
     * 订单地区分布
     * @return array
     */
    public static function getOrderArea()
    {
        $data = OrderModel::getOrderArea();
        $datas = getAreaData($data);
        return ['count' => count($data), 'datas' => $datas];
    }

    /**
     * 订单总数
     * @param $where
     * @return int
     */
    public static function countOrder($where)
    {
        return OrderModel::countOrder($where);
    }

    /**
     * 市场需求数据
     * @return array
     */
    public static function getDemandData()
    {
        $where = ['type_id' => 16];
        // 成交总金额
        $totalPrice = sprintf("%.2f", self::orderTotalPayPrice($where));
        // 订单总数
        $orderCount = self::countOrder($where);
        // 当日订单总数
        $orderTodayCount = OrderModel::orderTodayTotalNums($where);

        $where1 = ['type' => 1];
        // 访问总人数
        $peopleCount = ResourceSaleClickShareService::countResourceSaleClickShare($where1);
        // 当日访问人数
        $peopleTodayCount = ResourceSaleClickShareService::countTodayResourceSaleClickShare($where1);

        return [
            'totalPrice' => $totalPrice,
            'orderCount' => $orderCount,
            'orderTodayCount' => $orderTodayCount,
            'peopleCount' => $peopleCount,
            'peopleTodayCount' => $peopleTodayCount,
        ];
    }

    /**
     * 单订单数据
     * @param $where
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function findOrder($where)
    {
        return OrderModel::findOrder($where);
    }

    /**
     * 营销中心-下单地区分布
     * @param $where
     * @param int $offset
     * @param int $length
     * @return array
     */
    public static function getMarketingOrderArea($where, $offset = 0, $length = 6)
    {
        return OrderModel::getMarketingOrderArea($where, $offset, $length);
    }

    /**
     * 营销中心-下单地区统计
     * @param $where
     * @return int
     */
    public static function totalMarketingOrderArea($where)
    {
        return OrderModel::totalMarketingOrderArea($where);
    }

    /**
     * 营销中心-金额累计
     * @param array $where
     * @return mixed
     */
    public static function sumMarketingOrderPrice($where = [])
    {
        return OrderModel::sumMarketingOrderPrice($where);
    }

    /**
     * 营销中心-过去7天活动金额
     * @param $where
     * @param $startTime
     * @param $endTime
     * @return array
     */
    public static function getMarketingOrderPrice($startTime, $endTime, $where)
    {
        return OrderModel::getMarketingOrderPrice($startTime, $endTime, $where);
    }

    /**
     * 营销中心-转换用户订单
     * @param $where
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getConvertMarketingOrder($where)
    {
        $data = OrderModel::getConvertMarketingOrder($where);
        $payData = '';
        foreach ($data as $k => $v) {
            $payData .= $v['price'] . '/<span class="color3">' . date('Y-m-d', $v['pay_time']) . '</span><br>';
        }

        return $payData ?: '-' . '/' . '-';
    }

    /**
     * 订单列表
     * @param $where
     * @param $page
     * @param $pagesize
     * @param $type 3=>收益  4=>支出  1=>订单
     * @return array
     */
    public static function getAllOrderList($where, $page, $pagesize, $type)
    {
        $list = OrderModel::getAllOrderList($where, $page, $pagesize);
        // type_id  17=>订单收益  18=>订单支出
        if ($type == 3) {
            foreach ($list as $k => $v) {
                // 用户ID/昵称
                $list[$k]['user_data'] = $v['uid'] . '<br><span class="color3">' . emojiDecode($v['nickname']) . '</span>';

                // 来源/订单类型
                $associate = $v['type_id'] != 17 ? ($v['associate'] == 1 ? '公众号' : '小程序') : '额外收益';
                $list[$k]['source_data'] = $associate . '<br><span class="color3">' . ($v['type_id'] != 17 ? $v['tname'] : '-') . '</span>';

                // 收入金额
                $list[$k]['price'] = '+' . $v['price'];

                // 入账时间
                $list[$k]['pay_time'] = $v['pay_time'] ? date('Y-m-d H:i', $v['pay_time']) : '-';

                // 备注
                $list[$k]['desc'] = $v['type_id'] != 17 ? '-' : $v['desc'];

                // 凭证
                $list[$k]['images'] = $v['images'] ? '<div><img style="border-radius: 0;" class="headimgs" title="点我查看原图" onclick="lookimg(this.src)" src="' . config('url.url') . $v['images'] . '" \' + \'alt=""></div>' : '-';
            }

        } elseif ($type == 4) {
            foreach ($list as $k => $v) {
                // 用户ID/昵称
                $list[$k]['user_data'] = $v['uid'] . '<br><span class="color3">' . emojiDecode($v['nickname']) . '</span>';

                // 支出金额
                $list[$k]['price'] = '-' . $v['price'];

                // 支出时间
                $list[$k]['refund_time'] = $v['refund_time'] ? date('Y-m-d H:i', $v['refund_time']) : '-';

                // 使用部门
                $department = '';
                if ($v['type_id'] == 18) {
                    $department = RoleService::findDepartmentValue(['id' => $v['mid']]);
                }
                $list[$k]['department'] = $department ?: '-';

                // 发票
                $list[$k]['images'] = $v['images'] ? '<div><img style="border-radius: 0;" class="headimgs" title="点我查看原图" onclick="lookimg(this.src)" src="' . config('url.url') . $v['images'] . '" \' + \'alt=""></div>' : '-';
            }

        } else {
            foreach ($list as $k => $v) {
                // 用户id/订单id
                $list[$k]['uids_data'] = $v['uid'] . '<br><span class="color3">' . ($v['order_no'] ?: '-') . '</span>';

                // 昵称/角色
                $role = getRoleName($v['role']);
                $list[$k]['nickname_data'] = emojiDecode($v['nickname']) . '<br><span class="color3">' . $role . '</span>';

                // 地区/身份（来源）
                $identity = UsersCateService::findUsersIdentity(['uid' => $v['uid']]);
                $identity = $identity ?: '游客';
                $associate = $v['type_id'] != 17 ? ($identity . '（' . ($v['associate'] == 1 ? '公众号' : '小程序') . '）') : '额外收益';
                $list[$k]['area_data'] = ($v['type_id'] != 17 ? $v['city'] : '-') . '<br><span class="color3">' . $associate . '</span>';

                // 订单类型/金额
                $price = $v['type_id'] == 1 ? $v['price'] . '（' . $v['level'] . '）' : $v['price'];
                $list[$k]['type_data'] = ($v['type_id'] != 17 ? $v['tname'] : '-') . '<br><span class="color3">' . $price . '</span>';

                // 提交/付费时间
                $pay_time = $v['pay_time'] ? date('Y-m-d H:i', $v['pay_time']) : '-';
                $create_time = $v['create_time'] ? date('Y-m-d H:i', strtotime($v['create_time'])) : '-';
                $list[$k]['submit_data'] = $create_time . '<br><span class="color3">' . $pay_time . '</span>';
            }
        }

        return $list;
    }

    /**
     * 订单列表统计
     * @param $where
     * @return int
     */
    public static function countAllOrderList($where)
    {
        return OrderModel::countAllOrderList($where);
    }

    /**
     * 统计所有订单
     * @return int
     */
    public static function countAllOrder()
    {
        return OrderModel::countAllOrder();
    }

    /**
     * 订单创建
     * @param $data
     * @return OrderModel|\think\Model\
     */
    public static function createOrder($data)
    {
        return OrderModel::createOrder($data);

    }
}